package com.heo.server;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
import com.heo.pojo.DeviceInfoEntity;
import com.heo.pojo.DeviceModelEntity;
import com.heo.pojo.JsonArgs;
import com.heo.pojo.OrgInfoEntity;
import com.heo.pojo.StatusDictEntity;
import com.heo.pub.ApplicationContextUtil;
import com.heo.pub.DictEnum;
import com.heo.service.DeviceInfoService;
import com.heo.service.DeviceModelService;
import com.heo.service.OrgInfoService;
import com.heo.service.StatusDictService;
import com.heo.thread.SendMessageTransparentThread;
import com.heo.util.ByteHelper;
import com.heo.util.DeviceNettyUtils;
import com.heo.util.GsonUtils;
import com.heo.util.NettyChannelMapUtils;
import com.heo.util.Utils;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * Created by zhangcf handler不是一个单例.即每个channel下都会有自己的一个handler实例.
 * 对于使用spring注解时，一定要注解该类为多例。否则通道断开再重新建立时，会提示 NettyServerHandler is not
 * a @Sharable handler, so can't be added or removed multiple times.
 */
@Component
@Scope("prototype")
public class NettyServerTransparentHandle extends SimpleChannelInboundHandler<String> {

	private static Logger logger = Logger.getLogger(NettyServerTransparentHandle.class);
	public ChannelHandlerContext mCtx;
	private String deviceImei = null;
	private String macAddress = null;
	private String query = ""; // 服务器与板子之间的查询
	private String receiveScriptEngine = "";
	private String sendScriptEngine = "";
	private String appId = "";
	private String callUrl = "";
	private Map<String, StatusDictEntity> statusDictMap;

	private String freeStatus = "";
	private String slotStatus = "";
	private String workStatus = "";
	private String startMatch = "";
	private String start = "";
	private String slotMatch = "";
	private String slot = "";
	private String deviceQuery = "";
	private int deviceType = 0;
	private int withoutCode;

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		this.mCtx = ctx;
	}
	
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
			throws Exception {
		logger.info(macAddress + " userEventTriggered channel close");
		ctx.close();
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		try {
			String jsonString = msg;
			JSONObject rspJsonMap = null;
			logger.info("macAddress = " + macAddress + ", read message = " + jsonString);
			JsonArgs jsonArgs = (JsonArgs) GsonUtils.jsonToObject(jsonString, JsonArgs.class);
			if (jsonArgs != null) {
				Integer option = jsonArgs.getO();
				if (Utils.checkNull(jsonArgs.getM())) {
					macAddress = jsonArgs.getM();
				}
				if (Utils.checkNull(option)) {
					rspJsonMap = new JSONObject();
					rspJsonMap.put("o", option);
					switch (option) {
					case 1:
						if (!Utils.checkNull(macAddress)) {
							throw new Exception(macAddress + "设备不存在请联系管理员!!");
						}
						// 初始化设备，并入库
						DeviceInfoService deviceInfoService = (DeviceInfoService) ApplicationContextUtil
								.getBeanById("deviceInfoService");
						DeviceModelService deviceModelService = (DeviceModelService) ApplicationContextUtil
								.getBeanById("deviceModelService");
						StatusDictService statusDictService = (StatusDictService) ApplicationContextUtil
								.getBeanById("statusDictService");
						OrgInfoService orgInfoService = (OrgInfoService) ApplicationContextUtil
								.getBeanById("orgInfoService");
						DeviceInfoEntity deviceInfo = deviceInfoService.getDeviceInfoMap(macAddress);
						if (deviceInfo == null) {
							throw new Exception(macAddress + "设备不存在请联系管理员!!");
						}
						deviceImei = deviceInfo.getDeviceImei();
						DeviceModelEntity deviceModel = deviceModelService
								.getDeviceModelMap(deviceInfo.getDeviceModelId());
						receiveScriptEngine = deviceModel.getReceivePretreatmentCode();
						sendScriptEngine = deviceModel.getSendPretreatmentCode();
						deviceInfoService.initDeviceInfo(jsonArgs);
						OrgInfoEntity orgInfoEntity = orgInfoService.getByKey(deviceInfo.getDeviceImei());
						appId = orgInfoEntity.getAppId();
						callUrl = orgInfoEntity.getCallUrl();
						NettyChannelMapUtils.add(appId, deviceInfo.getDeviceImei(), deviceInfo.getDeviceChannelNum(),
								Utils.getShort(deviceModel.getDeviceModel()), ctx.channel());
						DeviceNettyUtils.deviceInitResult(rspJsonMap);
						statusDictMap = statusDictService.getStatusDictMap(deviceModel.getDeviceModelId());
						sendMessage(rspJsonMap);

						if (deviceInfo != null) {
							deviceType = deviceModel.getDeviceModelId();
							// terminalType = Utils.getInt(washerInfo.get("TERMINAL_TYPE"));

							slot = DeviceNettyUtils.scriptEngineCmd(sendScriptEngine, Utils.SLOT);
							slotMatch = DeviceNettyUtils.scriptEngineCmd(sendScriptEngine, Utils.SLOT_MATCH);
							start = DeviceNettyUtils.scriptEngineCmd(sendScriptEngine, Utils.START);
							startMatch = DeviceNettyUtils.scriptEngineCmd(sendScriptEngine, Utils.START_MATCH);
							query = DeviceNettyUtils.scriptEngineCmd(sendScriptEngine, Utils.QUERY);
							freeStatus = DeviceNettyUtils.scriptEngineCmd(sendScriptEngine, Utils.FREE_STATUS);
							slotStatus = DeviceNettyUtils.scriptEngineCmd(sendScriptEngine, Utils.SLOT_STATUS);
							workStatus = DeviceNettyUtils.scriptEngineCmd(sendScriptEngine, Utils.WORK_STATUS);
							deviceQuery = DeviceNettyUtils.scriptEngineCmd(sendScriptEngine, Utils.DEVICE_QUERY);

							// NettyChannelMapTransparentUtils.getInstance().add(macAddress, this);
							// boolean startWasher = true;
							// Integer t = jsonArgs.getT();
							// // 如果是投币工作
							// if (Utils.checkNull(t)) {
							// optionTransparentService.outsideController(
							// macAddress, t, rspJsonMap);
							// startWasher = false;
							// }

							rspJsonMap.clear();
							rspJsonMap.put("h", query);
							// 海尔主板需要 轮询功能
							if (Utils.checkNull(deviceQuery)) {
								rspJsonMap.put("a", 150);
								rspJsonMap.put("o", 3);
							} else if (deviceType == 9) {
								rspJsonMap.clear();
								rspJsonMap.put("h", "056600002299");
							}
							if(Utils.checkNull(query)) {
								SendMessageTransparentThread sendMessageTransparentThread = new SendMessageTransparentThread(
										appId, deviceImei, rspJsonMap.toJSONString(), 5000);
								NettyChannelMapUtils.sendTaskThreadPool.execute(sendMessageTransparentThread);
							}
						} else {
							throw new Exception("设备不存在请联系管理员!!");
						}
						break;
					case 2:
						if (Utils.checkNull(query)) {
							rspJsonMap.put("h", query);
						} else {
							rspJsonMap.put("t", 150);
						}
						if (NettyChannelMapUtils.get(appId, deviceImei) == null) {
							close();
						}
						NettyChannelMapUtils.refreshDeviceControlInfoExpire(appId, deviceImei);// 设备有消息上来，在redis里做延期
						sendMessage(rspJsonMap);
						break;
					case 3:
						if (!Utils.checkNull(macAddress)) {
							throw new Exception("设备不存在请联系管理员!!");
						}
						rspJsonMap.put("t", 150); // 心跳
						String h = jsonArgs.getH();
						if (deviceType == 4) {
							// 洗衣机，摇摇机
//							if (terminalType == 1 || terminalType == 2) {
								if (Utils.checkNull(h)) {
									if (Utils.checkNull(slotMatch) && h.startsWith(slotMatch)) {
										Thread.sleep(3000);
										rspJsonMap.put("h", start);
										sendMessage(rspJsonMap);
//										String message = GsonUtils.objectToJson(rspJsonMap);
//										CheckTransparentThared checkTransparentThared = new CheckTransparentThared(macAddress, message, 5000);
//										new Thread(checkTransparentThared).start();
										SendMessageTransparentThread checkTransparentThared = new SendMessageTransparentThread(
												appId, deviceImei, rspJsonMap.toJSONString(), 5000);
										NettyChannelMapUtils.sendTaskThreadPool.execute(checkTransparentThared);
									} else if (Utils.checkNull(startMatch) && h.startsWith(startMatch)) {
										rspJsonMap.put("h", query);
										sendMessage(rspJsonMap);
//										String message = GsonUtils.objectToJson(rspJsonMap);
//										CheckTransparentThared checkTransparentThared = new CheckTransparentThared(macAddress, message, 8000);
//										new Thread(checkTransparentThared).start();
										SendMessageTransparentThread checkTransparentThared = new SendMessageTransparentThread(
												appId, deviceImei, rspJsonMap.toJSONString(), 8000);
										NettyChannelMapUtils.sendTaskThreadPool.execute(checkTransparentThared);
									} else if (Utils.checkNull(query) && h.startsWith(query)) {
										String cmd = "";
//										int s = -1;
										if (freeStatus.equals(h)) {
											cmd = "01";
//											s = 1; // 空闲中
										} else if (workStatus.equals(h)) {
											cmd = "00";
//											s = 0; // 工作中
										} else if (slotStatus.equals(h)) {
											cmd = "03";
//											s = 3; // 投币中
										}
//										if (s >= 0) {
										if (Utils.checkNull(cmd)) {
//											optionTransparentService.deviceController(macAddress, Utils.getInteger(s), rspJsonMap);
											NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, cmd, callUrl, statusDictMap);
											sendMessage(rspJsonMap);
										} else {
											if (h.length() > 2) {
												String ss = h.substring(h.length() - 2, h.length());
												if (Utils.checkNull(ss)) {
//													optionTransparentService.errorCodeOption(macAddress, ss);
													NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, ss, callUrl, statusDictMap);
												}
											}
											rspJsonMap.put("t", 140); // 错误心跳
											sendMessage(rspJsonMap);
										}
									} else {
										sendMessage(rspJsonMap);
									}
								} else {
//									if (isQuery == 0) {
//										rspJsonMap.put("h", query);
//									}
									sendMessage(rspJsonMap);
								}
//							}
//							// 按摩椅模式
//							else if (terminalType == 9) {
//								if (h.startsWith(startMatch)) {
//									int s = -1;
//									if (freeStatus.equals(h)) {
//										s = 1; // 空闲中
//									} else if (workStatus.equals(h)) {
//										s = 0; // 工作中
//									} else if (slotStatus.equals(h)) {
//										s = 3; // 投币中
//									}
//									if (s >= 0) {
//										optionTransparentService.deviceController(macAddress, Utils.getInteger(s),
//												rspJsonMap);
//										sendMessage(rspJsonMap);
//									} else {
//										if (h.length() > 2) {
//											String ss = h.substring(h.length() - 2, h.length());
//											if (Utils.checkNull(ss)) {
//												optionTransparentService.errorCodeOption(macAddress, ss);
//											}
//										}
//										rspJsonMap.put("t", 140); // 错误心跳
//										sendMessage(rspJsonMap);
//									}
//								} else {
//									sendMessage(rspJsonMap);
//								}
//							} else {
//								sendMessage(rspJsonMap);
//							}
								//循环投币
						} else if (deviceType == 16) {
							if (Utils.checkNull(h)) {
								if (h.startsWith(query)) {
									if (freeStatus.equals(h)) {
//										optionTransparentService.deviceChuiFengJiController(macAddress, Utils.getInteger(1), rspJsonMap);
										NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, "01", callUrl, statusDictMap);
									} else if (workStatus.equals(h)) {
										sendMessage(rspJsonMap);
//										optionTransparentService.deviceChuiFengJiController(macAddress, Utils.getInteger(0), rspJsonMap);
										NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, "00", callUrl, statusDictMap);
										Thread.sleep(10000);
//										optionTransparentService.deviceChuiFengJiController(macAddress, Utils.getInteger(1), rspJsonMap);
										NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, "01", callUrl, statusDictMap);
									}
								}
							}
							sendMessage(rspJsonMap);
						} else if (deviceType == 3) {
							if (Utils.checkNull(h)) {
								if (h.equals(slotMatch)) {
									rspJsonMap.put("h", query);
								} else if (h.length() > 32) {
									if (h.length() > 36) {
										String er = h.substring(34, 36);
										if ((Utils.checkNull(er) && !"21".equals(er) && !"F1".equals(er))
												&& ("51".equals(er) || "71".equals(er) || "41".equals(er)
														|| "E1".equals(er))) {
//											optionTransparentService.errorCodeOption(macAddress, er);
											NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, er, callUrl, statusDictMap);
										}
									}
									// 洗衣机32-34字节表示状态
									String ss = h.substring(32, 34);
									// 烘干机34字节返回 24-26表示状态
									if (h.length() == 34) {
										ss = h.substring(24, 26);
									}
//									int s = -1;
									String cmd = "";
									if ("01".equals(ss) || "00".equals(ss) || "0E".equals(ss)) {
										cmd = "01";
//										s = 1; // 空闲中
									} else if ("02".equals(ss) || "03".equals(ss) || "05".equals(ss) || "06".equals(ss)
											|| "07".equals(ss) || "08".equals(ss) || "09".equals(ss) || "0A".equals(ss)
											|| "0B".equals(ss)) {
//										s = 0; // 工作中
										cmd = "00";
									}
//									if (s >= 0) {
									if(Utils.checkNull(cmd)) {
//										optionTransparentService.deviceController(macAddress, Utils.getInteger(s), rspJsonMap);
										NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, cmd, callUrl, statusDictMap);
									}
								} else if (workStatus.equals(h)) {
//									optionTransparentService.deviceController(macAddress, Utils.getInteger(0), rspJsonMap);
									NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, "00", callUrl, statusDictMap);
								}
							}
							sendMessage(rspJsonMap);
						} else if (deviceType == 14) {
							if (Utils.checkNull(h)) {
								if (h.length() > 20) {
									String er = h.substring(8, 10);
									if (Utils.checkNull(er) && ("E4".equals(er) || "E3".equals(er) || "E2".equals(er)
											|| "E1".equals(er) || "E0".equals(er))) {
//										optionTransparentService.errorCodeOption(macAddress, er);
										NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, er, callUrl, statusDictMap);
									} else {
										String ss = h.substring(4, 6);
//										int s = -1;
										String cmd = "";
										if ("30".equals(ss)) {
//											s = 1; // 空闲中
											cmd = "01";
										} else if ("32".equals(ss) || "33".equals(ss) || "34".equals(ss)
												|| "35".equals(ss) || "36".equals(ss)) {
//											s = 0; // 工作中
											cmd = "00";
										}
//										if (s >= 0) {
										if(Utils.checkNull(cmd)) {
//											optionTransparentService.deviceController(macAddress, Utils.getInteger(s), rspJsonMap);
											NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, cmd, callUrl, statusDictMap);
										}
									}
								}
								sendMessage(rspJsonMap);
							}
						} else if (deviceType == 9) {
							if (Utils.checkNull(h)) {
								int length = h.length();
								if (h.length() > 2) {
									String end = h.substring(length - 2, length);
									if ("45".equals(end)) {
										String withoutCodeStr = h.substring(2, length - 2);
										if (Utils.checkNull(withoutCodeStr)) {
											withoutCode = ByteHelper.hex16To10(withoutCodeStr);
//											moduleWithoutService.updateWithoutCode(macAddress, withoutCode + "");
											rspJsonMap.clear();
											StringBuilder sBuilder = new StringBuilder("0C66");
											sBuilder.append(ByteHelper.hexIntegerToBytes(withoutCode, 4));
											sBuilder.append("88");
											sBuilder.append(Utils.getInitStr());
											sBuilder.append("99");
											String initTime = sBuilder.toString();
											rspJsonMap.put("h", initTime);
										}
									} else {
										String cmd = h.substring(6, 8);
										if ("66".equals(cmd) && length == 20) {
											String cardStr = h.substring(8, 14);
											String balance = h.substring(14, 18);
											String card = ByteHelper.hex16To10(cardStr, 5);
											Map<String, Object> balanceMap = new HashMap<String, Object>();//optionTransparentService.queryBalance(card);
											if (balanceMap == null) {
												StringBuilder sBuilder = new StringBuilder("0C66");
												sBuilder.append(ByteHelper.hexIntegerToBytes(withoutCode, 4));
												sBuilder.append("55");
												sBuilder.append(cardStr);
												sBuilder.append("0000000000");
												String cmdCode = sBuilder.toString();
												rspJsonMap.put("h", cmdCode);
											} else {
												int balanceInt = Utils.getInteger(balanceMap.get("balance"));
												int status = Utils.getInteger(balanceMap.get("STATUS"));
												logger.info("机器号：" + withoutCode + "，卡号：" + card + ", 余额："
														+ Integer.parseInt(balance, 16) + "分，充值金额：" + balanceInt + "分");
												rspJsonMap.clear();
												StringBuilder sBuilder = new StringBuilder("0C66");
												sBuilder.append(ByteHelper.hexIntegerToBytes(withoutCode, 4));
												if (1 == status) {
													sBuilder.append("66");
												} else {
													sBuilder.append("11");
												}
												sBuilder.append(cardStr);
												sBuilder.append(ByteHelper.hexIntegerToBytes(balanceInt, 4));
												sBuilder.append(ByteHelper.hexIntegerToBytes(balanceInt, 4));
												sBuilder.append(Utils.initRechargeCheck(balance));
												String cmdCode = sBuilder.toString();
												rspJsonMap.put("h", cmdCode);
											}
										} else if ("33".equals(cmd) && length == 20) {
											String cardStr = h.substring(8, 14);
											String card = ByteHelper.hex16To10(cardStr, 5);
//											optionTransparentService.balanceSuccess(card);
										}
									}
								}
							}
							rspJsonMap.put("o", 3);
							sendMessage(rspJsonMap);
						} // 碧控洗衣机
						else if (deviceType == 15) {
							if (Utils.checkNull(h)) {
								if (h.length() >= 20) {
									if (h.startsWith("66")) {
										String ss = h.substring(18, 20);
										if (h.equals("660902000000000000010A") || "01".equals(ss) || "03".equals(ss)
												|| "04".equals(ss) || "05".equals(ss)) {
											// 工作中
//											optionTransparentService.deviceController(macAddress, 0, rspJsonMap);
											NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, "00", callUrl, statusDictMap);
										}
									} else if (h.startsWith("EE0A")) {
//										optionTransparentService.deviceController(macAddress, 1, rspJsonMap);
										NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, "01", callUrl, statusDictMap);
									} else {
										String er = h.substring(18, 20);
										if (Utils.checkNull(er) && ("01".equals(er) || "02".equals(er))) {
//											optionTransparentService.errorCodeOption(macAddress, "BK" + er);
											NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, er, callUrl, statusDictMap);
										}
									}
								}
								sendMessage(rspJsonMap);
							}
						} // 长江洗衣机
						else if (deviceType == 11) {
							if (Utils.checkNull(h)) {
								if (h.startsWith("39")) {
									// 390281F06CCD 代表洗衣板收到指令
									if (h.equals("390281F06CCD")) {
										rspJsonMap.put("h", query);
									} else {
										String ss = h.substring(6, 8);
										if ("04".equals(ss)) {
											String er = h.substring(16, 18);
											if (!"".equals(er)) {
//												optionTransparentService.errorCodeOption(macAddress, "CJ" + er);
												NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, er, callUrl, statusDictMap);
											}
										} else {
											String cmd = "";
//											int s = -1;
											if ("01".equals(ss)) {
//												s = 1; // 空闲中
												cmd = "01"; // 空闲中
											} else if ("02".equals(ss)) {
//												s = 0; // 工作中
												cmd = "00"; // 工作中
											}
//											if (s >= 0) {
											if (Utils.checkNull(cmd)) {
//												optionTransparentService.deviceController(macAddress, Utils.getInteger(s), rspJsonMap);
												NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, cmd, callUrl, statusDictMap);
											}
										}
									}
								}
								sendMessage(rspJsonMap);
							}
						} // 凤凰洗衣机
						else if (deviceType == 12) {
							if (Utils.checkNull(h)) {
								if (h.startsWith("11111111")) {
									String ss = h.substring(8, 12);
									if ("0A01".equals(ss)) {
										String er = h.substring(20, 22);
										if (!"00".equals(er)) {
//											optionTransparentService.errorCodeOption(macAddress, "FH" + er);
											NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, er, callUrl, statusDictMap);
										} else {
											String cmd = "";
											ss = h.substring(18, 20);
											if ("00".equals(ss)) {
												cmd = "01"; // 空闲中
											} else if ("01".equals(ss) || "02".equals(ss) || "03".equals(ss)
													|| "04".equals(ss) || "08".equals(ss)) {
												cmd = "00"; // 工作中
											}
											if (Utils.checkNull(cmd)) {
//												optionTransparentService.deviceController(macAddress, Utils.getInteger(s), rspJsonMap);
												NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, cmd, callUrl, statusDictMap);
											}
										}
									}
								}
								sendMessage(rspJsonMap);
							}
						} else if (deviceType == 13) {
							if (Utils.checkNull(h)) {
								if (h.startsWith("AA0BB2")) {
									sendMessage(rspJsonMap);
//									optionTransparentService.deviceChuiFengJiController(macAddress, Utils.getInteger(0), rspJsonMap);
									NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, "00", callUrl, statusDictMap);
									Thread.sleep(5000);
//									optionTransparentService.deviceChuiFengJiController(macAddress, Utils.getInteger(1), rspJsonMap);
									NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, "01", callUrl, statusDictMap);
								} else {
									sendMessage(rspJsonMap);
								}
							}
						} // 弗尼亚洗衣机
						else if (deviceType == 8) {
							if (Utils.checkNull(h)) {
								if (h.equals("A5E20000") || h.equals("A5E00000") || h.equals("A5E10000") || h.equals("A5E30000") || h.equals("A5E40000")) {
									String er = h.substring(2, 4);
//									optionTransparentService.errorCodeOption(macAddress, "FNY" + er);
//								} else if (h.equals("A5E00000")) {
//									String er = h.substring(2, 4);
//									optionTransparentService.errorCodeOption(macAddress, "FNY" + er);
//								} else if (h.equals("A5E10000")) {
//									String er = h.substring(2, 4);
//									optionTransparentService.errorCodeOption(macAddress, "FNY" + er);
//								} else if (h.equals("A5E30000")) {
//									String er = h.substring(2, 4);
//									optionTransparentService.errorCodeOption(macAddress, "FNY" + er);
//								} else if (h.equals("A5E40000")) {
//									String er = h.substring(2, 4);
//									optionTransparentService.errorCodeOption(macAddress, "FNY" + er);
									NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, er, callUrl, statusDictMap);
								} else if (h.startsWith("A531") || h.startsWith("A5CC")) {
									String ss = h.substring(6, 8);
									int s = -1;
									if ("A0".equals(ss) || "B0".equals(ss) || "C0".equals(ss) || "D0".equals(ss)) {
										s = 0; // 工作中
									} else if ("A5CC0000".equals(h)) {
										s = 0; // 工作中
									}
									if (s >= 0) {
//										optionTransparentService.deviceController(macAddress, Utils.getInteger(s), rspJsonMap);
										NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, "00", callUrl, statusDictMap);
									}
								} else if (h.startsWith("A5300000")) {
//									int s = 1;
//									optionTransparentService.deviceController(macAddress, Utils.getInteger(s), rspJsonMap);
									NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, "01", callUrl, statusDictMap);
								}
							} // 杭州碧空洗衣机
							else if (deviceType == 14) {
								if (Utils.checkNull(h)) {
									String code = h.substring(2, 4);
									if("84".equals(code)) {
										String status = h.substring(6, 8);
										if("05".equals(status) || "06".equals(status)) {
											NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, status, callUrl, statusDictMap);
										}else if("00".equals(status)) {
											NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, "01", callUrl, statusDictMap);
										}else if("01".equals(status) || "02".equals(status) || "03".equals(status) || "04".equals(status)){
											NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, "00", callUrl, statusDictMap);
										}
									} else if("85".equals(code)) {
										String status = h.substring(6, 10);
										//拒绝接收
										if("0000".equals(status)) {
											NettyChannelMapUtils.callBackSendStatus(appId, deviceImei, 0, DictEnum.CallBackType.STATUS_REPORT, "01", callUrl, statusDictMap);
										} else {
											rspJsonMap.put("h", "AA85020000AB");
										}
									}
								}
							}
							sendMessage(rspJsonMap);
						}
						break;
					}
				} else {
					throw new Exception("设备不存在请联系管理员!!");
				}
			} else {
				throw new Exception("参数不正确");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			NettyChannelMapUtils.remove(appId, deviceImei);
			close();
		}
	}

	/**
	 * 发送消息
	 * 
	 * @param rspJsonMap
	 * @throws Exception
	 */
	public synchronized void sendMessage(JSONObject rspJsonMap) throws Exception {
		if (rspJsonMap != null && rspJsonMap.size() > 0 && mCtx != null) {
			String rspJson = rspJsonMap.toJSONString();
			mCtx.writeAndFlush(rspJson + "\n");
			logger.info("macAddress=" + macAddress + ", send message = " + rspJson);
		}
	}

	public void close() throws IOException {
		if (mCtx != null) {
			NettyChannelMapUtils.remove(appId, deviceImei);
			mCtx.close();
			mCtx = null;
		}
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		super.channelReadComplete(ctx);
		// 刷新挂起的数据到远端
		ctx.writeAndFlush(Unpooled.EMPTY_BUFFER);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		logger.info(cause.getMessage());
		logger.info(macAddress + " exceptionCaught channel close");
		ctx.close();
	}
}
